import React from 'react';
import { Link } from 'react-router-dom';
import { PlusIcon, BookOpenIcon, TagIcon, PenTool } from 'lucide-react';
import { useDiaryStore } from '../store/diaryStore';
import { format } from 'date-fns';
import { ChartProvider } from '../contexts/ChartContext';
import {
  EntriesOverTimeChart,
  MoodDistributionChart,
  PopularTagsChart,
  TemplateUsageChart,
  WritingStreakChart
} from '../components/charts';
import HeatmapCalendar from '../components/charts/HeatmapCalendar';
import MoodRadarChart from '../components/charts/MoodRadarChart';
import TagTreemapChart from '../components/charts/TagTreemapChart';
import ComparativeAnalytics from '../components/charts/ComparativeAnalytics';
import ChartCustomization from '../components/charts/ChartCustomization';

const motivationalQuotes = [
  "Every day is a new page in your story.",
  "Your thoughts today become your memories tomorrow.",
  "Writing is the painting of the voice.",
  "The best time to plant a tree was 20 years ago. The second best time is now.",
  "In the end, we will remember not the words of our enemies, but the silence of our friends."
];

const getRandomQuote = () => {
  return motivationalQuotes[Math.floor(Math.random() * motivationalQuotes.length)];
};

function HomeContent() {
  const { getRecentEntries, getStats } = useDiaryStore();
  const recentEntries = getRecentEntries(3);
  const stats = getStats();
  const today = new Date();
  const greeting = getGreeting();
  
  function getGreeting() {
    const hour = new Date().getHours();
    if (hour < 12) return 'Good morning';
    if (hour < 17) return 'Good afternoon';
    return 'Good evening';
  }
  
  const formatEntryDate = (dateString: string) => {
    try {
      return format(new Date(dateString), 'MMM dd, yyyy');
    } catch {
      return dateString;
    }
  };
  
  const truncateContent = (content: string, maxLength: number = 100) => {
    const textContent = content.replace(/<[^>]*>/g, ''); // Remove HTML tags
    return textContent.length > maxLength 
      ? textContent.substring(0, maxLength) + '...'
      : textContent;
  };

  return (
    <div className="max-w-6xl mx-auto space-y-8">
      {/* Welcome Section */}
      <div className="card">
        <div className="text-center">
          <h1 className="text-3xl font-inter font-bold text-forest-green mb-2">
            {greeting}! 👋
          </h1>
          <p className="text-lg text-warm-gray mb-4">
            {format(today, 'EEEE, MMMM do, yyyy')}
          </p>
          <p className="text-sage italic">
            "{getRandomQuote()}"
          </p>
        </div>
      </div>
      
      {/* Dashboard Charts */}
      <div className="space-y-8 mb-8">
        {/* Activity Heatmap - Full Width */}
        <div className="grid grid-cols-1 gap-6">
          <HeatmapCalendar />
        </div>
        
        {/* Top Row - Time-based Charts */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <EntriesOverTimeChart />
          <WritingStreakChart />
        </div>
        
        {/* Middle Row - Advanced Analytics */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <MoodRadarChart />
          <TagTreemapChart />
        </div>
        
        {/* Comparative Analytics */}
        <ComparativeAnalytics />
        
        {/* Bottom Row - Distribution Charts */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <MoodDistributionChart />
          <TemplateUsageChart />
        </div>
        
        {/* Tags Chart */}
        <div className="grid grid-cols-1 gap-6">
          <PopularTagsChart />
        </div>
        
        {/* Quick Stats Summary */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-gradient-to-r from-forest-green-50 to-forest-green-100 rounded-lg p-4 border border-forest-green-200">
            <div className="flex items-center">
              <BookOpenIcon className="h-6 w-6 text-forest-green-600" />
              <div className="ml-3">
                <p className="text-xl font-bold text-forest-green-800">{stats.totalEntries}</p>
                <p className="text-forest-green-600 text-sm">Total Entries</p>
              </div>
            </div>
          </div>
          
          <div className="bg-gradient-to-r from-sage-50 to-sage-100 rounded-lg p-4 border border-sage-200">
            <div className="flex items-center">
              <TagIcon className="h-6 w-6 text-sage-600" />
              <div className="ml-3">
                <p className="text-xl font-bold text-sage-800">{stats.entriesThisMonth}</p>
                <p className="text-sage-600 text-sm">This Month</p>
              </div>
            </div>
          </div>
          
          <div className="bg-gradient-to-r from-warm-gray-50 to-warm-gray-100 rounded-lg p-4 border border-warm-gray-200">
            <div className="flex items-center">
              <div className="h-6 w-6 bg-forest-green-100 rounded-full flex items-center justify-center">
                <span className="text-forest-green-600 font-bold text-xs">{stats.longestStreak}</span>
              </div>
              <div className="ml-3">
                <p className="text-xl font-bold text-warm-gray-800">{stats.longestStreak}</p>
                <p className="text-warm-gray-600 text-sm">Longest Streak</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      {/* Recent Entries */}
      <div className="card">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-inter font-semibold text-forest-green">
            Recent Entries
          </h2>
          <Link to="/entries" className="text-sage hover:text-forest-green transition-colors">
            View all →
          </Link>
        </div>
        
        {recentEntries.length === 0 ? (
          <div className="text-center py-8">
            <PenTool className="w-12 h-12 text-sage mx-auto mb-4" />
            <p className="text-warm-gray mb-4">No entries yet. Start your journey!</p>
            <Link to="/write" className="btn-primary">
              Write Your First Entry
            </Link>
          </div>
        ) : (
          <div className="space-y-4">
            {recentEntries.map((entry) => (
              <Link
                key={entry.id}
                to={`/entry/${entry.id}`}
                className="block p-4 border border-gray-200 rounded-lg hover:border-sage hover:shadow-md transition-all duration-200"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <h3 className="font-inter font-medium text-forest-green mb-1">
                      {entry.title || 'Untitled Entry'}
                    </h3>
                    <p className="text-warm-gray text-sm mb-2">
                      {truncateContent(entry.content)}
                    </p>
                    <div className="flex items-center gap-4 text-xs text-sage">
                      <span>{formatEntryDate(entry.date)}</span>
                      {entry.mood && (
                        <span className="flex items-center gap-1">
                          <span>Mood: {entry.mood}</span>
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
      
      {/* Quick Actions */}
      <div className="flex justify-center">
        <Link to="/write" className="btn-primary text-lg px-8 py-3">
          <PenTool className="w-5 h-5 mr-2 inline" />
          Write New Entry
        </Link>
      </div>
    </div>
  );
}

export default function Home() {
  return (
    <ChartProvider>
      <div className="min-h-screen bg-warm-gray-50 chart-dashboard">
        <HomeContent />
        <ChartCustomization />
      </div>
    </ChartProvider>
  );
}